import React, { useEffect } from "react";
import { Modal, Form, Input, message, Button } from "antd";

interface SupplierValues {
  supplier_name: string;
  contact: string;
  // 合作条件
  cooperation_conditions: string;
}

interface SupplierModalProps {
  title: string;
  visible: boolean;
  onCancel: () => void;
  onOk: (values: any) => void;
  defaultValue?: any;
}

const SupplierModal: React.FC<SupplierModalProps> = ({
  title,
  visible,
  onCancel,
  onOk,
  defaultValue,
}) => {
  const [form] = Form.useForm<SupplierValues>();

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      onOk(values);
      form.resetFields();
    } catch (errorInfo) {
      console.log("Failed:", errorInfo);
    }
  };

  useEffect(() => {
    if (Object.keys(defaultValue).length === 0) {
      form.resetFields();
    } else {
      form.setFieldsValue({
        ...defaultValue,
      });
    }
  }, [defaultValue, visible]);

  return (
    <Modal
      title={title}
      visible={visible}
      onOk={handleOk}
      onCancel={onCancel}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button key="ok" type="primary" onClick={handleOk}>
          确定
        </Button>,
      ]}
    >
      <Form form={form}>
        <Form.Item
          label="供应商名称"
          name="supplier_name"
          rules={[
            {
              required: true,
              whitespace: true,
              message: "请输入供应商名称",
            },
          ]}
          validateTrigger="onBlur"
        >
          <Input placeholder="请输入供应商名称" />
        </Form.Item>
      
        <Form.Item
          label="联系"
          name="contact"
          rules={[
            {
              required: false,
              message: "请输入联系电话",
            },
          ]}
          validateTrigger="onBlur"
        >
          <Input placeholder="请输入联系电话" />
        </Form.Item>

        <Form.Item
          label="合作条件"
          name="cooperation_conditions"
          rules={[
            {
              required: true,
              whitespace: true,
              message: "请输入合作条件",
            },
          ]}
          validateTrigger="onBlur"
        >
          <Input placeholder="请输入合作条件" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default SupplierModal;
